package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.SenateScoreView;
import com.xmy.cultivate.mapper.SenateScoreMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 教务积分 服务实现类
 * </p>
 *
 * @author hpiggy
 * @since 2024-10-26
 */
@Service
public class SenateScoreServiceImpl extends ServiceImpl<SenateScoreMapper, SenateScore> implements ISenateScoreService {

    @Autowired
    SenateScoreMapper senateScoreMapper;

    @Autowired
    ISenateScoreSetService iSenateScoreSetService;

    @Autowired
    IdWorker idWorker;

    @Autowired
    ISenateDepartScoreSetService iSenateDepartScoreSetService;

    @Autowired
    ISenateDepartService iSenateDepartService;

    @Autowired
    ITrackMarketService iTrackMarketService;

    @Autowired
    IRadeFiducialService iRadeFiducialService;

    @Autowired
    IRadeFiducialSetService iRadeFiducialSetService;

    @Autowired
    IRadeDataService iRadeDataService;

    @Override
    public boolean addOrUpdateSenateScoreData(SenateScoreView senateScoreView) {
        try {
            SenateScoreSet senateScoreSet = iSenateScoreSetService.getSenateScoreSetOne(senateScoreView.getYearPart(), senateScoreView.getQuarterNum(), null, senateScoreView.getSubjectsId(), senateScoreView.getProjectsId());
            if (senateScoreSet != null) {
                QueryWrapper<SenateScore> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", senateScoreView.getYearPart());
                queryWrapper.eq("quarter_num", senateScoreView.getQuarterNum());
                if (senateScoreView.getTeacherId() != null) {
                    queryWrapper.eq("teacher_id", senateScoreView.getTeacherId());
                } else if (senateScoreView.getSchoolId() != null) {
                    queryWrapper.eq("school_id", senateScoreView.getSchoolId());
                }
                queryWrapper.eq("projects_id", senateScoreView.getProjectsId());
                if (senateScoreSet.getStatisticsType().equals(1)) {
                    //按率计算
                    queryWrapper.eq("lesson_num", senateScoreView.getLessonNum());
                } else if (senateScoreSet.getStatisticsType().equals(2)) {
                    //按数量计算
                }
                queryWrapper.last("limit 1");
                SenateScore senateScore = this.senateScoreMapper.selectOne(queryWrapper);

                Integer score = 0;
                if (senateScore == null) {
                    senateScore = new SenateScore();
                    senateScore.setId(idWorker.nextId());
                    senateScore.setScore(score);
                    senateScore.setUpdatedAt(LocalDateTime.now().withNano(0));
                }
                if (senateScoreView.getRadeNum().compareTo(senateScoreSet.getStatisticsCount()) >= 0) {
                    score = senateScoreSet.getIntegral();
                }

                //如果传过去的不为空，就使用传过来的值，例如请假补课率，全部到课，没有请假的也加1分，就直接传1过来
                if (senateScoreView.getScore() != null) {
                    score = senateScoreView.getScore();
                }

                if (senateScore.getScore().equals(0) && score > 0) {
                    senateScore.setUpdatedAt(LocalDateTime.now().withNano(0));
                }
                senateScore.setScore(score);
                senateScore.setCount(senateScoreView.getRadeNum());
                senateScore.setYearPart(senateScoreView.getYearPart());
                senateScore.setQuarterNum(senateScoreView.getQuarterNum());
                senateScore.setLessonNum(senateScoreView.getLessonNum());
                if (senateScoreView.getTeacherId() != null) {
                    senateScore.setTeacherId(senateScoreView.getTeacherId());
                    senateScore.setType(1);
                } else if (senateScoreView.getSchoolId() != null) {
                    senateScore.setSchoolId(senateScoreView.getSchoolId());
                    senateScore.setType(4);
                }
                senateScore.setSubjectsId(senateScoreView.getSubjectsId());
                senateScore.setProjectsId(senateScoreView.getProjectsId());
                senateScore.setScore(score);
                this.saveOrUpdate(senateScore);
            }
        } catch (Exception e) {
        }
        return true;
    }


    /**
     * 保存积分
     */
    @Override
    public boolean addOrUpdateSenateScoreDataNew(SenateScoreView senateScoreView) {
        try {
            TrackMarket trackMarket = new TrackMarket();
            if (senateScoreView.getScoreType() == 2) {
                QueryWrapper<TrackMarket> trackMarketQueryWrapper = new QueryWrapper<>();
                trackMarketQueryWrapper.eq("year_part", senateScoreView.getYearPart());
                trackMarketQueryWrapper.eq("quarter_num", senateScoreView.getQuarterNum());
                trackMarketQueryWrapper.eq("track_type", 2);
                trackMarketQueryWrapper.eq("status", 1);
                trackMarketQueryWrapper.eq("school_type", senateScoreView.getSchoolType());
                trackMarketQueryWrapper.eq("classify", senateScoreView.getClassify());
                trackMarketQueryWrapper.orderByDesc("id");
                trackMarketQueryWrapper.last("limit 1");
                if (senateScoreView.getYearClassId() != null) {
                    trackMarketQueryWrapper.eq("year_class_id", senateScoreView.getYearClassId());
                } else {
                    trackMarketQueryWrapper.isNull("year_class_id");
                }
                if (senateScoreView.getSchoolId() != null) {
                    trackMarketQueryWrapper.eq("school_id", senateScoreView.getSchoolId());
                }
                trackMarket = iTrackMarketService.getOne(trackMarketQueryWrapper);

                if (trackMarket == null) {
                    return false;
                }
            }

            SenateDepartScoreSet scoreSet = iSenateDepartScoreSetService.getOne(
                    new QueryWrapper<SenateDepartScoreSet>()
                            .eq("tag", senateScoreView.getTag())
                            .eq("score_type", senateScoreView.getScoreType())
                            .last("limit 1"));

            if (scoreSet != null) {
                QueryWrapper<SenateScore> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("year_part", senateScoreView.getYearPart());
                queryWrapper.eq("quarter_num", senateScoreView.getQuarterNum());
                if (senateScoreView.getYearClassId() != null) {
                    queryWrapper.eq("year_class_id", senateScoreView.getYearClassId());
                } else {
                    queryWrapper.isNull("year_class_id");
                }
                if (senateScoreView.getSubjectsId() != null) {
                    queryWrapper.eq("subjects_id", senateScoreView.getSubjectsId());
                }
                if (senateScoreView.getTeacherId() != null) {
                    queryWrapper.eq("teacher_id", senateScoreView.getTeacherId());
                } else if (senateScoreView.getSchoolId() != null) {
                    queryWrapper.eq("school_id", senateScoreView.getSchoolId());
                }
                if (senateScoreView.getType() != null) {
                    queryWrapper.eq("type", senateScoreView.getType());
                }
                if (senateScoreView.getScoreType() == 2) {
                    queryWrapper.eq("team_id", trackMarket.getId());
                }
                queryWrapper.eq("projects_id", senateScoreView.getProjectsId());
                queryWrapper.eq("lesson_num", senateScoreView.getLessonNum());
                queryWrapper.last("limit 1");
                SenateScore senateScore = this.senateScoreMapper.selectOne(queryWrapper);

                Integer score = 0;
                if (senateScore == null) {
                    senateScore = new SenateScore();
                    senateScore.setId(idWorker.nextId());
                    senateScore.setScore(score);
                    senateScore.setUpdatedAt(LocalDateTime.now().withNano(0));
                }

                if (senateScoreView.getScoreType() == 1) {
                    if (senateScoreView.getRadeNum().compareTo(scoreSet.getStatisticsCount()) >= 0) {
                        score = scoreSet.getIntegral();
                    }
                } else if (senateScoreView.getScoreType() == 2) {
                    int rank = senateScoreView.getRadeNum().intValue();
                    if (senateScoreView.getSchoolType() == 1) {
                        String rankIntegral = scoreSet.getRankIntegralBig();
                        String[] scores = rankIntegral.split(",");
                        if (rank > 0 && rank <= scores.length) {
                            score = Integer.parseInt(scores[rank - 1]);
                            senateScore.setScore(score);
                        }
                    } else if (senateScoreView.getSchoolType() == 2) {
                        String rankIntegral = scoreSet.getRankIntegral();
                        String[] scores = rankIntegral.split(",");
                        if (rank > 0 && rank <= scores.length) {
                            score = Integer.parseInt(scores[rank - 1]);
                            senateScore.setScore(score);
                        }
                    }

                    senateScore.setTeamId(trackMarket.getId());
                }

                //如果传过去的不为空，就使用传过来的值，例如请假补课率，全部到课，没有请假的也加1分，就直接传1过来
                if (senateScoreView.getScore() != null) {
                    score = senateScoreView.getScore();
                }

                if (senateScore.getScore().equals(0) && score > 0) {
                    senateScore.setUpdatedAt(LocalDateTime.now().withNano(0));
                }
                if (senateScoreView.getYearClassId() != null) {
                    senateScore.setYearClassId(senateScoreView.getYearClassId());
                }
                if (senateScoreView.getScoreType() == 2) {
                    senateScore.setScoreType(3);
                }
                if (senateScoreView.getType() != null) {
                    senateScore.setType(senateScoreView.getType());
                }
                if (senateScoreView.getSchoolId() != null) {
                    senateScore.setSchoolId(senateScoreView.getSchoolId());
                }
                if (senateScoreView.getTeacherId() != null) {
                    senateScore.setTeacherId(senateScoreView.getTeacherId());
                }
                senateScore.setScore(score);
                senateScore.setCount(senateScoreView.getRadeNum());
                senateScore.setYearPart(senateScoreView.getYearPart());
                senateScore.setQuarterNum(senateScoreView.getQuarterNum());
                senateScore.setLessonNum(senateScoreView.getLessonNum());
                senateScore.setSubjectsId(senateScoreView.getSubjectsId());
                senateScore.setProjectsId(senateScoreView.getProjectsId());
                this.saveOrUpdate(senateScore);
            }
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * 保存基准值
     */
    @Override
    public boolean addOrUpdateRadeFiducialData(RadeFiducial fiducial) {
        try {
            QueryWrapper<RadeFiducial> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("year_part", fiducial.getYearPart());
            queryWrapper.eq("quarter_num", fiducial.getQuarterNum());
            queryWrapper.eq("projects_id", fiducial.getProjectsId());
            queryWrapper.eq("subjects_id", fiducial.getSubjectsId());
            if (fiducial.getLessonNum() != null) {
                queryWrapper.eq("lesson_num", fiducial.getLessonNum());
            }
            queryWrapper.eq("lesson_type", fiducial.getLessonType());
            queryWrapper.last("limit 1");
            RadeFiducial radeFiducial = iRadeFiducialService.getOne(queryWrapper);

            if (radeFiducial == null) {
                radeFiducial = new RadeFiducial();
                radeFiducial.setId(idWorker.nextId());
            }

            radeFiducial.setYearPart(fiducial.getYearPart());
            radeFiducial.setQuarterNum(fiducial.getQuarterNum());
            radeFiducial.setSubjectsId(fiducial.getSubjectsId());
            radeFiducial.setLessonType(fiducial.getLessonType());
            radeFiducial.setProjectsId(fiducial.getProjectsId());
            radeFiducial.setProjectsName(fiducial.getProjectsName());
            if (fiducial.getLessonNum() != null) {
                radeFiducial.setLessonNum(fiducial.getLessonNum());
            }
            radeFiducial.setRadeNum(fiducial.getRadeNum());
            radeFiducial.setRadeAll(fiducial.getRadeAll());
            radeFiducial.setFiducialSetId(fiducial.getFiducialSetId());
            iRadeFiducialService.saveOrUpdate(radeFiducial);
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * 保存各项率数据
     */
    @Override
    public boolean addOrUpdateRadeData(RadeData data) {
        try {
            QueryWrapper<RadeData> queryWrapper = new QueryWrapper<>();

            if (data.getYearClassId() != null) {
                queryWrapper.eq("year_class_id", data.getYearClassId());
            }
            if (data.getTeacherId() != null) {
                queryWrapper.eq("teacher_id", data.getTeacherId());
            }
            if (data.getExamNum() != null) {
                queryWrapper.eq("exam_num", data.getExamNum());
            }
            if (data.getLessonNum() != null) {
                queryWrapper.eq("lesson_num", data.getLessonNum());
            }
            if (data.getSubjectsId() != null) {
                queryWrapper.eq("subjects_id", data.getSubjectsId());
            }

            queryWrapper.eq("year_part", data.getYearPart());
            queryWrapper.eq("quarter_num", data.getQuarterNum());
            queryWrapper.eq("school_id", data.getSchoolId());
            queryWrapper.eq("lesson_type", data.getLessonType());
            queryWrapper.eq("projects_id", data.getProjectsId());
            queryWrapper.eq("stat_type", data.getStatType());
            queryWrapper.last("limit 1");
            RadeData radeData = iRadeDataService.getOne(queryWrapper);

            if (radeData == null) {
                radeData = new RadeData();
                radeData.setId(idWorker.nextId());
            } else {
                radeData.setUpdateAt(LocalDateTime.now().withNano(0));
            }

            if (data.getYearClassId() != null) {
                radeData.setYearClassId(data.getYearClassId());
            }
            if (data.getTeacherId() != null) {
                radeData.setTeacherId(data.getTeacherId());
            }
            if (data.getRadeMolecule() != null) {
                radeData.setRadeMolecule(data.getRadeMolecule());
            }
            if (data.getRadeDenominator() != null) {
                radeData.setRadeDenominator(data.getRadeDenominator());
            }
            if (data.getRadeNum() != null) {
                radeData.setRadeNum(data.getRadeNum());
            }
            if (data.getRankNum() != null) {
                radeData.setRankNum(data.getRankNum());
            }
            if (data.getExamNum() != null) {
                radeData.setExamNum(data.getExamNum());
            }
            if (data.getLessonNum() != null) {
                radeData.setLessonNum(data.getLessonNum());
            }
            if (data.getSubjectsId() != null) {
                radeData.setSubjectsId(data.getSubjectsId());
            }
            if (data.getRadeMolecule02() != null) {
                radeData.setRadeMolecule02(data.getRadeMolecule02());
            }
            if (data.getRadeDenominator02() != null) {
                radeData.setRadeDenominator02(data.getRadeDenominator02());
            }
            radeData.setYearPart(data.getYearPart());
            radeData.setQuarterNum(data.getQuarterNum());
            radeData.setSchoolId(data.getSchoolId());
            radeData.setLessonType(data.getLessonType());
            radeData.setFiducialSetId(data.getFiducialSetId());
            radeData.setProjectsId(data.getProjectsId());
            radeData.setStatType(data.getStatType());// 统计类型，6：按四大校区，2：校区老师
            iRadeDataService.saveOrUpdate(radeData);
        } catch (Exception e) {
        }
        return true;
    }

}
